import {
  Component,
  OnInit,
  ViewChild,
  TemplateRef,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
} from '@angular/core';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { tap, map } from 'rxjs/operators';
import { STComponent, STColumn, STData, STChange } from '@delon/abc';
import { OrderService } from '../order.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'tablepanel',
  templateUrl: './tablepanel.component.html',
  styleUrls: ['./tablepanel.component.css']
})
export class TablepanelComponent implements OnInit {
  form: FormGroup;
  submitting = false;
  
  showDetail(tpl: TemplateRef<{}>, item: any): any {
    this.modalSrv.create({
      nzTitle: '订单详情',
      nzContent: tpl,
      nzOnOk: () => {
        for (const i in this.form.controls) {
          this.form.controls[i].markAsDirty();
          this.form.controls[i].updateValueAndValidity();
        }
        if (this.form.invalid) return false;

        this.submitting = true;
        this.orderService.shipping(this.form.value).subscribe(
          res => {
            this.submitting = false;
            if (res.success) {
              this.msg.success(`操作成功`);
              this.getData();
            }
          },
          err => {
            this.submitting = false;
            this.msg.error(`操作失败`);
          },
        );
      },
    });
  }

  q: any = {
    pi: 1,
    ps: 10,
    sorter: '',
    status: null,
    statusList: [],
  };
  data: any[] = [];
  loading = false;
  status = [
    { index: 0, text: '关闭', value: false, type: 'default', checked: false },
    {
      index: 6,
      text: '运行中',
      value: false,
      type: 'processing',
      checked: false,
    },
    { index: 2, text: '已上线', value: false, type: 'success', checked: false },
    { index: 97, text: '异常', value: false, type: 'error', checked: false },
  ];

  @ViewChild('modalContent')
  modalContent: TemplateRef<{}>;

  @ViewChild('st')
  st: STComponent;
  columns: STColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    { title: '订单号', index: 'orderNo' },
    { title: '商品名称', index: 'skuName' },
    { title: '商品照片', index: 'imgUrl', type: 'img' },
    {
      title: '状态',
      index: 'statusName',
      // render: 'status',
      // filter: {
      //   menus: this.status,
      //   fn: (filter: any, record: any) => record.status === filter.index,
      // },
    },
    {
      title: '金额',
      index: 'receivableAmount',
    },
    {
      title: '创建时间',
      index: 'createTime',
    },
    {
      title: '操作',
      buttons: [
        {
          text: '详情',
          click: (item: any) => this.showDetail(this.modalContent, item)
        },
      ],
    },
  ];
  selectedRows: STData[] = [];
  description = '';
  totalCallNo = 0;
  expandForm = false;

  constructor(
    private http: _HttpClient,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private cdr: ChangeDetectorRef,
    private orderService: OrderService,
    private fb: FormBuilder
  ) {}

  ngOnInit() {
    this.getData();

    this.form = this.fb.group({
      shopName: [null, [Validators.required]],
      brandIntroduction: [null, [Validators.required]],
      telephone: [null, [Validators.required]],
      shopAddress: [null, [Validators.required]],
    });
  }

  getData() {
    this.loading = true;
    this.q.statusList = this.status
      .filter(w => w.checked)
      .map(item => item.index);

    if (this.q.status !== null && this.q.status > -1)
      this.q.statusList.push(this.q.status);

    this.loading = false;

    /*
    this.http
      .get('/rule', this.q)
      .pipe(
        map((list: any[]) =>
          list.map(i => {
            const statusItem = this.status[i.status];
            i.statusText = statusItem.text;
            i.statusType = statusItem.type;
            return i;
          }),
        ),
        tap(() => (this.loading = false)),
      )
      .subscribe(res => {
        this.data = res;
        this.cdr.detectChanges();
      });
    */

    this.orderService.queryOrderList().subscribe(resp => {
      if(resp.success) {
        let obj;

        this.data = [];
        resp.data.list.forEach(element => {
          obj = element;
          obj.imgUrl = element.skuInfoList[0].imgUrl;
          obj.skuName = element.skuInfoList[0].skuName;
          
          if(obj.status == 1)
            obj.statusName = "待付款";

          if(obj.status == 2)
            obj.statusName = "待发货";

          if(obj.status == 6)
            obj.statusName = "待收货";

          if(obj.status == 71)
            obj.statusName = "已收货";

          if(obj.status == 97)
            obj.statusName = "已取消";

          this.data.push(obj);
        });
      }
    });
  }

  stChange(e: STChange) {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox;
        this.totalCallNo = this.selectedRows.reduce(
          (total, cv) => total + cv.callNo,
          0,
        );
        this.cdr.detectChanges();
        break;
      case 'filter':
        this.getData();
        break;
    }
  }

  remove() {
    this.http
      .delete('/rule', { nos: this.selectedRows.map(i => i.no).join(',') })
      .subscribe(() => {
        this.getData();
        this.st.clearCheck();
      });
  }

  approval() {
    this.msg.success(`审批了 ${this.selectedRows.length} 笔`);
  }

  add(tpl: TemplateRef<{}>) {
    this.modalSrv.create({
      nzTitle: '新建规则',
      nzContent: tpl,
      nzOnOk: () => {
        this.loading = true;
        this.http
          .post('/rule', { description: this.description })
          .subscribe(() => this.getData());
      },
    });
  }

  reset() {
    // wait form reset updated finished
    setTimeout(() => this.getData());
  }

}
